<template>
  <view class="climber-home">
    <!-- 服务状态开关 -->
    <view class="status-section">
      <text class="status-label">服务状态</text>
      <view class="status-switch">
        <switch :checked="serviceEnabled" @change="onServiceToggle" color="#07c160" />
        <text class="status-text" :class="{ active: serviceEnabled }">{{ serviceEnabled ? '在线接单中' : '已下线' }}</text>
      </view>
      <text class="status-hint">关闭后将无法接收新订单</text>
    </view>

    <!-- 收入与订单统计 -->
    <view class="stats-row">
      <view class="stat-item">
        <text class="stat-icon">📊</text>
        <text class="stat-label">今日单量</text>
        <view class="stat-value-row">
          <text class="stat-value">{{ todayStats.orderCount }}</text>
          <text class="stat-change up">↑ {{ todayStats.orderGrowth }}%</text>
        </view>
        <text class="stat-compare">较昨日增长</text>
      </view>
      <view class="stat-item">
        <text class="stat-icon">💰</text>
        <text class="stat-label">本月收入</text>
        <view class="stat-value-row">
          <text class="stat-value">¥{{ monthStats.income }}</text>
          <text class="stat-change up">↑ {{ monthStats.growth }}%</text>
        </view>
        <text class="stat-compare">较上月增长</text>
      </view>
      <view class="stat-item" @tap="goIncomeList">
        <text class="stat-icon">💵</text>
        <text class="stat-label">可提现余额</text>
        <view class="stat-value-row">
          <text class="stat-value">¥{{ incomeStats.withdrawable }}</text>
        </view>
        <text class="stat-compare">查看收入明细 ›</text>
      </view>
    </view>

    <!-- 附近订单 -->
    <view class="orders-section">
      <view class="section-header">
        <text class="section-title">附近订单</text>
        <view class="filter-tabs">
          <text 
            v-for="(tab, index) in filterTabs" 
            :key="index"
            class="filter-tab" 
            :class="{ active: activeFilter === index }"
            @tap="changeFilter(index)"
          >
            {{ tab }}
          </text>
        </view>
      </view>

      <!-- 订单列表 -->
      <view class="order-list">
        <view v-if="!nearbyOrders.length" class="empty">
          <text class="empty-icon">📭</text>
          <text class="empty-text">暂无附近订单</text>
        </view>
        <view v-else class="order-card" v-for="order in nearbyOrders" :key="order.id">
          <view class="order-header">
            <view class="order-title-group">
              <text class="order-user">{{ order.userName }}</text>
              <text class="order-title">{{ order.title }}</text>
            </view>
            <text class="order-price">¥{{ order.price }}</text>
          </view>
          <view class="order-info">
            <view class="info-row" v-if="order.userPhone">
              <text class="info-icon">📞</text>
              <text class="info-text">{{ order.userPhone }}</text>
            </view>
            <view class="info-row">
              <text class="info-icon">⏰</text>
              <text class="info-text">{{ order.time }}</text>
            </view>
            <view class="info-row">
              <text class="info-icon">📍</text>
              <text class="info-text">{{ order.location }}</text>
            </view>
            <view class="info-row">
              <text class="info-icon">👥</text>
              <text class="info-text">{{ order.people }}</text>
            </view>
          </view>
          <view class="order-footer">
            <view class="tags">
              <text class="tag">{{ order.distance }}</text>
              <text class="tag">预计{{ order.duration }}</text>
            </view>
            <view class="actions">
              <button class="btn-ignore" size="mini" @tap="ignoreOrder(order)">忽略</button>
              <button class="btn-accept" size="mini" @tap="acceptOrder(order)">接单</button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部占位 -->
    <view class="tabbar-placeholder"></view>
    
    <!-- Tabbar -->
    <climber-tabbar :active="0" />
  </view>
</template>

<script>
import ClimberTabbar from '@/components/climber-tabbar/climber-tabbar.vue'
import { getNearbyOrders, acceptOrder as acceptOrderApi } from '@/api/order'
import { getIncomeSummary } from '@/api/income'

export default {
  components: { ClimberTabbar },
  data() {
    return {
      serviceEnabled: true,
      todayStats: {
        orderCount: 3,
        orderGrowth: 12
      },
      monthStats: {
        income: '0.00',
        growth: 8
      },
      incomeStats: {
        today: '0.00',
        withdrawable: '0.00'
      },
      filterTabs: ['全部', '距离', '价格'],
      activeFilter: 0,
      nearbyOrders: [] // 从接口获取订单数据
    }
  },
  onLoad() {
    this.loadIncomeSummary()
    this.loadNearbyOrders()
  },
  methods: {
    onServiceToggle(e) {
      this.serviceEnabled = e.detail.value
      if (this.serviceEnabled) {
        this.$modal.showToast('已开启在线接单')
      } else {
        this.$modal.showToast('已关闭接单服务')
      }
    },
    changeFilter(index) {
      this.activeFilter = index
      // TODO: 根据筛选条件重新加载订单
    },
    async loadIncomeSummary() {
      try {
        const res = await getIncomeSummary()
        if (res && res.code === 200 && res.data) {
          const val = Number(res.data.monthIncome || 0)
          this.monthStats.income = val.toFixed(2)
          this.incomeStats.today = Number(res.data.todayIncome || 0).toFixed(2)
          this.incomeStats.withdrawable = Number(res.data.withdrawableAmount || 0).toFixed(2)
        }
      } catch (e) {
        console.error('加载收入失败:', e)
      }
    },
    goIncomeList() {
      uni.navigateTo({ url: '/pages/income/list' })
    },
    async loadNearbyOrders() {
      try {
        const response = await getNearbyOrders()
        if (response.code === 200 && response.data) {
          // 将后端返回的订单数据转换为页面需要的格式
          this.nearbyOrders = response.data.map(order => this.convertOrderFormat(order))
        } else {
          this.nearbyOrders = []
        }
      } catch (error) {
        console.error('加载订单失败:', error)
        this.$modal.showToast('加载订单失败')
        this.nearbyOrders = []
      }
    },
    
    // 转换订单数据格式
    convertOrderFormat(order) {
      // 格式化时间
      const formatTime = (date, start, end) => {
        if (!date || !start || !end) return '时间待定'
        const dateStr = date.replace(/-/g, '/')
        return `${dateStr} ${start}-${end}`
      }
      
      // 计算时长
      const calculateDuration = (start, end) => {
        if (!start || !end) return '待定'
        const [startH, startM] = start.split(':').map(Number)
        const [endH, endM] = end.split(':').map(Number)
        const minutes = (endH * 60 + endM) - (startH * 60 + startM)
        const hours = Math.floor(minutes / 60)
        const mins = minutes % 60
        if (hours > 0 && mins > 0) {
          return `${hours}小时${mins}分钟`
        } else if (hours > 0) {
          return `${hours}小时`
        } else {
          return `${mins}分钟`
        }
      }
      
      return {
        id: order.id,
        userName: order.userName || '用户',
        userPhone: order.userPhone || '',
        title: order.routePlan || '登山服务',
        price: order.amount || 0,
        time: formatTime(order.serviceDate, order.startTime, order.endTime),
        location: order.routePlan || '黄山风景区',
        people: `${order.participantCount || 1}人`,
        distance: order.orderStatus === 'PENDING' ? '待接单' : order.orderStatus === 'CONFIRMED' ? '已确认' : '进行中',
        duration: calculateDuration(order.startTime, order.endTime),
        orderNo: order.orderNo,
        orderStatus: order.orderStatus
      }
    },
    ignoreOrder(order) {
      this.$modal.showToast('已忽略订单')
      this.nearbyOrders = this.nearbyOrders.filter(o => o.id !== order.id)
    },
    async acceptOrder(order) {
      uni.showModal({
        title: '确认接单',
        content: `确定接受订单"${order.title}"吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              this.$modal.loading('接单中...')
              const response = await acceptOrderApi(order.id)
              this.$modal.closeLoading()
              
              if (response.code === 200) {
                this.$modal.showToast('接单成功')
                // 重新加载订单列表
                await this.loadNearbyOrders()
              } else {
                this.$modal.showToast(response.msg || '接单失败')
              }
            } catch (error) {
              this.$modal.closeLoading()
              console.error('接单失败:', error)
              this.$modal.showToast('接单失败，请重试')
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.climber-home {
  min-height: 100vh;
  background: #f5f6f7;
}

/* 服务状态 */
.status-section {
  background: #fff;
  padding: 32rpx;
  margin-bottom: 20rpx;
}

.status-label {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.status-switch {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.status-text {
  margin-left: 16rpx;
  font-size: 28rpx;
  color: #999;
}

.status-text.active {
  color: #07c160;
  font-weight: 600;
}

.status-hint {
  font-size: 24rpx;
  color: #999;
}

/* 统计行 */
.stats-row {
  display: flex;
  gap: 20rpx;
  padding: 0 32rpx;
  margin-bottom: 20rpx;
}

.stat-item {
  flex: 1;
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
}

.stat-icon {
  font-size: 40rpx;
  display: block;
  margin-bottom: 12rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 12rpx;
}

.stat-value-row {
  display: flex;
  align-items: baseline;
  margin-bottom: 8rpx;
}

.stat-value {
  font-size: 40rpx;
  font-weight: 700;
  color: #333;
  margin-right: 12rpx;
}

.stat-change {
  font-size: 24rpx;
  color: #07c160;
}

.stat-change.up::before {
  content: '↑ ';
}

.stat-compare {
  font-size: 22rpx;
  color: #999;
}

/* 订单区域 */
.orders-section {
  background: #fff;
  margin: 0 32rpx;
  border-radius: 16rpx;
  padding: 24rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
}

.filter-tabs {
  display: flex;
  gap: 16rpx;
}

.filter-tab {
  font-size: 26rpx;
  color: #666;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  background: #f5f6f7;
}

.filter-tab.active {
  background: #1989fa;
  color: #fff;
}

/* 订单列表 */
.order-list {
  min-height: 400rpx;
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.order-card {
  background: #f9fafb;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.order-title-group {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.order-user {
  font-size: 28rpx;
  font-weight: 700;
  color: #333;
  margin-bottom: 4rpx;
}

.order-title {
  font-size: 24rpx;
  font-weight: 400;
  color: #666;
}

.order-price {
  font-size: 36rpx;
  font-weight: 700;
  color: #ff6b00;
}

.order-info {
  margin-bottom: 16rpx;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.info-icon {
  font-size: 28rpx;
  margin-right: 8rpx;
}

.info-text {
  font-size: 26rpx;
  color: #666;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tags {
  display: flex;
  gap: 12rpx;
}

.tag {
  font-size: 22rpx;
  color: #ff9500;
  background: #fff3e0;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
}

.actions {
  display: flex;
  gap: 16rpx;
}

.btn-ignore {
  background: #f5f6f7;
  color: #666;
  border: none;
  padding: 10rpx 24rpx;
  border-radius: 8rpx;
}

.btn-accept {
  background: #1989fa;
  color: #fff;
  border: none;
  padding: 10rpx 24rpx;
  border-radius: 8rpx;
}

/* 底部占位 */
.tabbar-placeholder {
  height: 120rpx;
}
</style>

